package com.suixun.service.impl;

import java.util.Date;

import javax.annotation.Resource;

import com.suixun.enums.ShowEnum;
import org.apache.commons.lang.StringUtils;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.stereotype.Service;

import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.baomidou.mybatisplus.mapper.Wrapper;
import com.baomidou.mybatisplus.service.impl.ServiceImpl;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.suixun.dao.InstructionsMapper;
import com.suixun.dao.redis.RedisDao;
import com.suixun.domain.Instructions;
import com.suixun.exceptions.SuixunException;
import com.suixun.service.InstructionsService;
import com.suixun.utils.ListUtil;

/**
 * <p>
 * 操作指南 服务实现类
 * </p>
 *
 * @author jacky
 * @since 2018-01-11
 */
@Service
public class InstructionsServiceImpl extends ServiceImpl<InstructionsMapper, Instructions>
        implements InstructionsService {

    @Resource
    private RedisDao redisDao;

    @Override
    @Cacheable(value = "instructionsCache", key = "'instructions_page_' + #page + '_' + #size + '_' + #title + '_' + #type + '_' + #isShow")
    public PageInfo<Instructions> pageInstructions(int page, int size, String title, Integer type, Integer isShow) {
        PageHelper.startPage(page, size);
        Wrapper<Instructions> wrapper = new EntityWrapper<>();
        if (StringUtils.isNotBlank(title)) {
            wrapper.like("title", title);
        }
        if (type != null) {
            wrapper.eq("type", type);
        }
        if(isShow != null && ShowEnum.containType(isShow)) {
            wrapper.eq("is_show", isShow);
        }
        return new PageInfo<>(this.selectList(wrapper));
    }

    @Override
    @Cacheable(value = "instructionsCache", key = "'instructions_getById_' + #id")
    public Instructions getById(Integer id) {
        return this.selectById(id);
    }

    @Override
    public void insert(Instructions instructions, Boolean isTop) {
        if (isTop != null && isTop) {
            instructions.setTop(String.valueOf(new Date().getTime()));
        }
        this.insert(instructions);

        redisDao.flushCaches("instructions*");
    }

    @Override
    public void update(Instructions instructions, Boolean isTop) {
        if (instructions.getId() == null) {
            throw new SuixunException("id不能为空");
        }
        Date date = new Date();
        if (isTop != null) {
            if (isTop) {
                instructions.setTop(String.valueOf(date.getTime()));
            } else {
                instructions.setTop("0");
            }
        }

        this.updateById(instructions);

        redisDao.flushCaches("instructions*");
    }

    @Override
    public void delete(String ids) {

        this.deleteBatchIds(ListUtil.Integers2List(ids));

        redisDao.flushCaches("instructions*");
    }
}
